package com.wr.springbootadmin.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author 王瑞
 * @description: 线程池配置 这里配置了两个线程池  一个负责处理异步任务  一个负责多线程任务调度
 * @date 2021/1/26  16:27
 */
@Configuration
public class ThreadPoolConfig {

    //核心线程数
    private Integer poolSize = 5;
    //最大线程数
    private Integer maxPoolSize = 10;
    //队列数
    private Integer queueCapacity = 20;
    //线程空闲后最大存活时间
    private Integer awaitTerminationSeconds=60;


    //这个线程池负责处理异步任务 这个线程池可配合@Scheduled 支持多种类型的计划任务，包含cron、fixDelay、fixRate等 方法可以异步执行
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor configThreadPool(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //核心线程数量
        threadPoolTaskExecutor.setCorePoolSize(poolSize);
        //最大线程数量
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        //队列中最大任务数
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        //线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("异步ThreadPool-");
        //当达到最大线程数时如何处理新任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程空闲后最大存活时间
        threadPoolTaskExecutor.setKeepAliveSeconds(awaitTerminationSeconds);
        //初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }



    // 这个线程池负责多线程任务调度
    @Bean("taskScheduler")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        executor.setPoolSize(poolSize);
        executor.setThreadNamePrefix("任务调度ThreadPool-");
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        return executor;
    }

    /* @Descreption:taskScheduler功能描述:
     * 〈使用方式==>〉:
     *                                      QuartzJob是自定义的线程类 必须实现Runnable接口,线程逻辑就写在run方法里
     * threadPoolTaskScheduler.schedule(new QuartzJob(), new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
            *                         cronStr是cron表达式的字符串
                return new CronTrigger(cronStr).nextExecutionTime(triggerContext);
            }
        });
     *
     * @return:
     * @Author: 王瑞
     * @Date: 2021/1/26 16:55
     */

}
